package campus.aiit.ssl.controller;

import campus.aiit.ssl.domain.model.User;
import campus.aiit.ssl.service.IndexService;
import campus.aiit.ssl.service.UserService;
import com.iflytek.uaac.client.rest.context.UaacServiceContext;
import io.swagger.annotations.*;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ihaokun
 * @date 2019/12/31 16:50
 */
@Api(value = "UserController", description = "用户相关api")
@RestController
public class UserController {
  @Resource private UserService userService;
  @Resource StringEncryptor encryptor;

  @ApiOperation("根据roleId获取用户列表")
  @GetMapping("/users/{roleId}")
  private List<User> users(@PathVariable byte roleId){
    return userService.list(roleId);
  }

  @ApiOperation("根据用户id获取用户信息与其管理的设备")
  @GetMapping("/users/{id}/devices")
  private User user(@PathVariable String id) throws Throwable {
    return userService.userWithDevices(id);
  }

  @ApiOperation(value="根据用户id获取用户信息与其管理的区域块" )
  @GetMapping("users/{id}/blocks")
  private User userWithBlocks(@PathVariable String id) throws Throwable {
      return userService.userWithBlocks(id);
  }

  @ApiOperation(value="添加用户" )
  @PostMapping("/users")
  private boolean add(@RequestBody User user) throws UserService.AlreadyException {
    return userService.add(user);
  }

  @ApiOperation(value="修改用户" )
  @PutMapping("/users")
  private boolean modify(@RequestBody User user) throws UserService.AlreadyException {
      return userService.modify(user);
  }

  @ApiOperation(value="删除用户" )
  @DeleteMapping("/users")
  private boolean remove(@RequestParam @Valid @NotEmpty String id){
    return userService.remove(id);
  }

  @ApiOperation(value="获取当前用户信息" )
  @PostMapping("/userInfo")
  public Map<String , Object> getUserInfo(HttpServletRequest request) {
    Map<String , Object> map = new HashMap<>();
    try {
      if(request.getSession().getAttribute("roleId").equals(2)){
        map = userService.getPropertyUserById((String) request.getSession().getAttribute("userId"));
        return map;
      }
    }catch (NullPointerException e){
      //System.out.println("空指针异常");
    }

    com.iflytek.uaac.common.domain.User user = UaacServiceContext.getUaacService().getCurrentUser(request.getSession());
    map.put("id",user.getLoginName());
    map.put("name",user.getName());
    int roleId = userService.userWithBlocks(user.getLoginName()).getRoleId();
    map.put("role_id",roleId);
    return map;
  }

  @ApiOperation(value="物业用户登陆" )
  @PostMapping("/propertyLogin")
  public Map propertyLogin(@RequestBody Map map, HttpServletRequest request)  {
    Map user = userService.getPropertyUserById((String) map.get("userId"));
    Map<String , Object> loginInfo = new HashMap<>();
    if (user == null) {
      loginInfo.put("status",2);
      loginInfo.put("info","no user");
      return loginInfo;
    }
    if(encryptor.decrypt((String) user.get("password")).equals((String) map.get("password"))){
      System.out.println("success");
      request.getSession().setAttribute("userId", map.get("userId"));
      request.getSession().setAttribute("roleId", 2);
      loginInfo.put("status",1);
      loginInfo.put("info","success");
      return loginInfo;
    }
    loginInfo.put("status",3);
    loginInfo.put("info","password error");
    return loginInfo;
  }

  @ApiOperation(value="获取物业用户列表" )
  @GetMapping("/propertyUser")
  private List<Map<String,Object>> getPropertyUser() {
    return userService.getPropertyUser();
  }

  @ApiOperation(value="通过userId获取物业用户信息" )
  @GetMapping("propertyUserById/{id}")
  private Map<String, Object> getPUser(@PathVariable String id){
      Map user = userService.getPropertyUserById(id);
      user.put("blocks",userService.pUserWithBlocks(id).get("blocks"));
      user.remove("password");
      return user;
  }

  @ApiOperation(value="添加物业用户" )
  @PostMapping("/propertyUser")
  private int addPropertyUser(@RequestBody Map map) {
    String userId = (String) map.get("userId");
    System.out.println(encryptor.encrypt("517883"));
    String regex = "^(?:\\+?86)?1(?:3\\d{3}|5[^4\\D]\\d{2}|8\\d{3}|7(?:[35678]\\d{2}|4(?:0\\d|1[0-2]|9\\d))|9[189]\\d{2}|66\\d{2})\\d{6}$";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher((String)map.get("userId"));
    if(!matcher.matches()){
//      System.out.println(matcher.matches());
      return 2;
    }
    String password = encryptor.encrypt(userId.substring(userId.length()-6));
    map.put("password",password);
    return userService.addPropertyUser(map);
  }

  @ApiOperation(value="修改物业用户" )
  @PutMapping("/propertyUser")
  private int updatePropertyUser(@RequestBody Map map) throws UserService.AlreadyException {
    String password = encryptor.encrypt((String) map.get("password"));
    map.put("password",password);
    return userService.updatePropertyUser(map);
  }

  @ApiOperation(value="删除物业用户" )
  @DeleteMapping("/propertyUser")
  private int delPropertyUser(@RequestParam @Valid @NotEmpty String id){
    return userService.delPropertyUser(id);
  }

  @ApiOperation(value="修改物业用户管理的区域块" )
  @PutMapping("pUser")
  private boolean modifyPUser(@RequestBody User user) throws UserService.AlreadyException {return userService.modifyForPUser(user);}

  @ApiOperation(value="删除物业用户管理的区域块" )
  @DeleteMapping("pUser")
  private boolean removePUserForBlocks(String id){
      return userService.removePUserForBlocks(id);
  }

}